//
//  RecViewController.swift
//

import UIKit
import JXCategoryView
import Alamofire

let space: CGFloat = 16.fit

class RecViewController: BaseViewController {
    
    enum RecFrom {
        case rec /// 推荐
        case song /// 唱儿歌
        case animation // 看动画
        case book /// 读绘本
        case story /// 听故事
        
        var path: String {
            switch self {
            case .rec:
                return "tj3"
            case .song:
                return "eg3"
            case .animation:
                return "dh3"
            case .book:
                return "hb3"
            case .story:
                return "gs3"
            }
        }
    }
    
    private var bannerHeight = (UIScreen.width - space * 2) * 0.5
    private var itemsHeight = ((UIScreen.width - space * 2 - 25.fit * 4) / 5) + 25.fit
    private var dataSource = [RecChildModel]()
    private var banners = [RecChildModel]()
    private var items = [RecChildModel]()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewSectionColorFlowLayout()
        layout.minimumLineSpacing = space
        layout.minimumInteritemSpacing = 10.fit
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.sysTableView
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(RecCell.self)
        collectionView.register(RecBigListCell.self)
        collectionView.register(RecBannerCell.self)
        collectionView.register(RecSlideCell.self)
        collectionView.register(RecHeaderItemCell.self)
        collectionView.register(RecStoreCell.self)
        collectionView.register(RecStoreListCell.self)
        collectionView.registerSectionHeader(RecSectionView.self)
        collectionView.registerSectionHeader(UICollectionViewSectionColorReusableView.self)
        collectionView.registerSectionFooter(UICollectionViewSectionColorReusableView.self)
        return collectionView
    }()
    
    private let from: RecFrom
    
    init(from: RecFrom) {
        self.from = from
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addSubviews()
    }

    private func addSubviews() {
        
        disablesAdjustScrollViewInsets(collectionView)
        
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(safeAreaLayoutGuideBottom)
        }
        
        collectionView.mj_headerRefresh { [weak self] in
            guard let `self` = self else { return }
            self.requestData()
        }
        
        collectionView.beginRefreshing()
    }

}

extension RecViewController {
    private func requestData() {
        Network.Home
            .list(path: from.path, age: 1)
            .request()
            .responseData(RecModel.self) { [weak self] (model) in
                guard let `self` = self else { return }
                self.collectionView.endHeaderRefresh()
                self.banners = model.result.top_items
                self.items = model.result.icon_items
                self.dataSource = model.result.more_items
                self.collectionView.reloadData()
        } failure: { [weak self] (error) in
            guard let `self` = self else { return }
            Toast.show(info: error.errorMessage)
            self.collectionView.endHeaderRefresh()
        }
    }
}

extension RecViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataSource.count + 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        if section == 1 {
            return 1
        }
        switch dataSource[section - 2].layoutType {
        case .slide:
            return 1
        default:
            return dataSource[section - 2].viewP.itemCount
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.section {
        case 0:
            let cell = collectionView.dequeueReusableCell(withClass: RecBannerCell.self, for: indexPath)
            cell.banners = banners
            return cell
        case 1:
            let cell = collectionView.dequeueReusableCell(withClass: RecHeaderItemCell.self, for: indexPath)
            cell.items = items
            return cell
        default:
            let model = dataSource[indexPath.section - 2]
            switch model.layoutType {
            case .big:
                let cell = collectionView.dequeueReusableCell(withClass: RecCell.self, for: indexPath)
                cell.update(big: model.data.items[indexPath.item])
                return cell
            case .big_list:
                let cell = collectionView.dequeueReusableCell(withClass: RecBigListCell.self, for: indexPath)
                cell.update(model.data.items[indexPath.item])
                return cell
            case .slide:
                let cell = collectionView.dequeueReusableCell(withClass: RecSlideCell.self, for: indexPath)
                cell.items = model.data.items.prefix(model.viewP.itemCount).map({ $0
                })
                return cell
            case .book:
                let cell = collectionView.dequeueReusableCell(withClass: RecBigListCell.self, for: indexPath)
                cell.update(slide: model.data.items[indexPath.item])
                return cell
            case .store:
                let cell = collectionView.dequeueReusableCell(withClass: RecStoreCell.self, for: indexPath)
                cell.update(model.data.items[indexPath.item])
                return cell
            case .store_list:
                let cell = collectionView.dequeueReusableCell(withClass: RecStoreListCell.self, for: indexPath)
                cell.update(model.data.items[indexPath.item])
                return cell
            case .hot:
                let cell = collectionView.dequeueReusableCell(withClass: RecCell.self, for: indexPath)
                cell.update(hot: model.data.items[indexPath.item])
                return cell
            default:
                let cell = collectionView.dequeueReusableCell(withClass: RecCell.self, for: indexPath)
                cell.update(model.data.items[indexPath.item])
                return cell
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        switch kind {
        case UICollectionView.elementKindSectionHeader:
            let view = collectionView.dequeueSectionHeader(withClass: RecSectionView.self, for: indexPath)
            switch indexPath.section {
            case 0, 1:
                view.titleLabel.text = ""
                view.rightLabel.text = ""
            default:
                let model = dataSource[indexPath.section - 2]
                view.titleLabel.text = model.title
                view.rightLabel.text = (model.viewP.itemCount > 1 && model.layoutType != .big_list) ? "更多" : ""
                view.didSelectedMore = { [weak self] in
                    guard let `self` = self else { return }
                    let vc = RecVideoMoreViewController()
                    vc.navTitle = model.title
                    vc.id = model.contentId
                    vc.atype = model.data.atype
                    vc.layoutType = model.layoutType
                    self.push(vc)
                }
            }
            return view
        case UICollectionView.elementKindSectionFooter:
            return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionViewSectionColorReusableView", for: indexPath)
        default:
            return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionViewSectionColorReusableView", for: indexPath)
        }
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard dataSource.count > 2 else { return }
        debugPrint(dataSource[indexPath.section - 2].layoutType)
        switch dataSource[indexPath.section - 2].layoutType {
        case .video:
            let model = dataSource[indexPath.section - 2].data.items[indexPath.item]
            let vc = PlayerViewController(url: model.url, id: model.subcateid)
            push(vc)
            for (index, _) in dataSource[indexPath.section - 2].data.items.enumerated() {
                dataSource[indexPath.section - 2].data.items[index].isSelected = false
            }
            dataSource[indexPath.section - 2].data.items[indexPath.item].isSelected = true
            VideoCacheManager.share.setVideo(dataSource[indexPath.section - 2].data, forKey: dataSource[indexPath.section - 2].data.subcateid)
        case .hot:
            let model = dataSource[indexPath.section - 2]
            let vc = RecVideoMoreViewController()
            vc.navTitle = model.data.items[indexPath.item].subcatename
            vc.id = model.data.items[indexPath.item].subcateid
            vc.layoutType = model.layoutType
            push(vc)
        case .store, .store_list, .audio_list:
            let model = dataSource[indexPath.section - 2].data
            let vc = RecAudioListViewController()
            vc.id = model.items[indexPath.item].id
            vc.atype = model.atype
            vc.outerid = model.items[indexPath.item].outerid
            push(vc)
        case .book:
            let model = dataSource[indexPath.section - 2].data.items[indexPath.item]
            Toast.maskLoading()
            for (index, _) in dataSource[indexPath.section - 2].data.items.enumerated() {
                dataSource[indexPath.section - 2].data.items[index].isSelected = false
            }
            dataSource[indexPath.section - 2].data.items[indexPath.item].isSelected = true
            BookCacheManager.share.setBook(dataSource[indexPath.section - 2].data, forKey: dataSource[indexPath.section - 2].data.id)
            ZipManager.share
                .downloadZipHandler(model.url) { progress in
                    debugPrint("下载进度: \(progress)")
            } unzipProgress: { progress in
                debugPrint("解压进度: \(progress)")
            } response: { bookModel in
                Toast.hide()
                if let model = bookModel {
                    let vc = ReadBookViewController(bookModel: model)
                    self.push(vc)
                } else {
                    Toast.show(info: "数据解析失败")
                }
            } failure: { error in
                Toast.show(info: error.errorMessage)
            }
        default:
            break
        }
    }
}

extension RecViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        switch indexPath.section {
        case 0:
            return CGSize(width: UIScreen.width - space * 2, height: banners.isEmpty ? 0.01 : bannerHeight)
        case 1:
            return CGSize(width: UIScreen.width - space * 2, height: items.isEmpty ? 0.01 : itemsHeight)
        default:
            let model = dataSource[indexPath.section - 2]
            switch model.layoutType {
            case .big:
                let width = UIScreen.width - space * 2
                return CGSize(width: width, height: width * 9 / 16 + 25.fit)
            case .big_list:
                let width = UIScreen.width - space * 2
                return CGSize(width: width, height: width * 8 / 23)
            case .slide:
                let height = (UIScreen.width - space * 2 - 30.fit) / 3 - 5.fit
                return CGSize(width: UIScreen.width, height: height * 5 / 4)
            case .book:
                let width = (UIScreen.width - space * 4) / 3
                return CGSize(width: width, height: width * 5 / 4)
            case .store:
                let width = (UIScreen.width - space * 4) / 3
                return CGSize(width: width, height: width)
            case .store_list:
                let height = (UIScreen.width - space * 4) / 3
                return CGSize(width: UIScreen.width - space, height: height)
            default:
                let width = (UIScreen.width - space * 3) / 2
                return CGSize(width: width, height: width * 9 / 16 + 25.fit)
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        switch section {
        case 0, 1:
            return CGSize(width: CGFloat.min, height: CGFloat.min)
        default:
            return CGSize(width: UIScreen.width, height: 44.fit)
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: CGFloat.min, height: CGFloat.min)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        switch section {
        case 0:
            return UIEdgeInsets(top: banners.isEmpty ? 0 : 10.fit, left: space, bottom: 0, right: space)
        case 1:
            return UIEdgeInsets(top: items.isEmpty ? 0 : 10.fit, left: space, bottom: 0, right: space)
        default:
            let model = dataSource[section - 2]
            switch model.layoutType {
            case .slide:
                return UIEdgeInsets(top: 10.fit, left: 0, bottom: 10.fit, right: 0)
            default:
                return UIEdgeInsets(top: 10.fit, left: space, bottom: 10.fit, right: space)
            }
        }
    }

}

extension RecViewController: UICollectionViewSectionColorDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColor section: Int) -> UIColor {
        return .white
    }
}

extension RecViewController: JXCategoryListContentViewDelegate {
    func listView() -> UIView! {
        return view
    }
}
